﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CML.Services.Interfaces;
using CML.Data;
using CML.Grammer;

namespace CML.Services.Implementations
{
	public class PropertyService : IPropertyService
	{
		//http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html

		public IList<Property> Parse(string raw)
		{
			var p = new PropertiesParser();
			return p.Parse(raw);
		}

		public string Escape(string key)
		{
			key = key.Replace(":", "\\:");
			key = key.Replace("=", "\\=");
			key = key.Replace(" ", "\\ ");
			return key;
		}

		public IList<Property> Escape(IList<Property> pl)
		{
			foreach (var p in pl)
			{
				p.key = Escape(p.key);
			}
			return pl;
		}

		public string UnEscape(string key)
		{
			key = key.Replace("\\:", ":");
			key = key.Replace("\\=", "=");
			key = key.Replace("\\ ", " ");
			return key;
		}

		public IList<Property> UnEscape(IList<Property> pl)
		{
			foreach (var p in pl)
			{
				p.key = UnEscape(p.key);
			}
			return pl;
		}

		public string Serialize(IList<Property> pl)
		{
			var s = new StringBuilder();
			foreach (var p in pl)
			{
				s.AppendLine(p.key + "=" + p.value);
			}
			return s.ToString();
		}
	}
}
